package com.jyl.practice;

import java.util.Stack;

/**
 * @ClassName Practice020
 * @Author admin
 * @Date 2024/6/14
 */
public class Practice020 {

    public static void main(String[] args) {
        String s1 = "()";
        String s2 = "[]";
        String s3 = "([";

        System.out.println(isValid(s1));
        System.out.println(isValid(s2));
        System.out.println(isValid(s3));
    }

    public static boolean isValid(String str) {
        Stack<Character> stack = new Stack<>();

        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (c == '(' || c == '[' || c == '{') {
                stack.push(c);
            } else if (stack.isEmpty()) {  // 若为关括号，则从栈中弹出 (确保栈中元素不为空)
                return false;
            } else {
                Character popValue = stack.pop();
                // 进行元素比较
                if (c == '}' && popValue != '(') {
                    return false;
                } else if (c == ']' && popValue != '[') {
                    return false;
                } else if (c == '}' && popValue != '{') {
                    return false;
                }
            }
        }
        return stack.isEmpty();

    }

}
